<template>
  <el-dialog :model-value="visible" @update:model-value="(value) => visible = value" :title="title" width="900px" :before-close="handleClose">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="项目编号" prop="projectCode">
            <el-input v-model="formData.projectCode" placeholder="请输入项目编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="水库名称" prop="reservoirName">
            <el-select v-model="formData.reservoirName" placeholder="请选择水库" filterable>
              <el-option label="东圳水库" value="东圳水库" />
              <el-option label="金钟水库" value="金钟水库" />
              <el-option label="西音水库" value="西音水库" />
              <el-option label="古洋水库" value="古洋水库" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="formData.projectName" placeholder="请输入项目名称" />
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="项目类型" prop="projectType">
            <el-select v-model="formData.projectType" placeholder="请选择项目类型">
              <el-option label="大坝加固" value="dam-reinforcement" />
              <el-option label="溢洪道改造" value="spillway-renovation" />
              <el-option label="输水设施" value="water-conveyance" />
              <el-option label="监测设施" value="monitoring-facility" />
              <el-option label="其他工程" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态">
              <el-option label="规划中" value="planning" />
              <el-option label="设计中" value="designing" />
              <el-option label="施工中" value="construction" />
              <el-option label="已完成" value="completed" />
              <el-option label="已暂停" value="paused" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开工时间" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              placeholder="选择开工时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="完工时间" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              type="date"
              placeholder="选择完工时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="投资金额" prop="investment">
            <el-input-number v-model="formData.investment" :min="0" placeholder="请输入投资金额" style="width: 100%" />
            <span style="margin-left: 8px; color: #999;">元</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="施工进度" prop="progress">
            <el-input-number v-model="formData.progress" :min="0" :max="100" placeholder="请输入施工进度" style="width: 100%" />
            <span style="margin-left: 8px; color: #999;">%</span>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="施工单位" prop="contractor">
            <el-input v-model="formData.contractor" placeholder="请输入施工单位" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="监理单位" prop="supervisor">
            <el-input v-model="formData.supervisor" placeholder="请输入监理单位" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="项目经理" prop="projectManager">
            <el-input v-model="formData.projectManager" placeholder="请输入项目经理" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设计单位" prop="designer">
            <el-input v-model="formData.designer" placeholder="请输入设计单位" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="质量等级" prop="qualityLevel">
            <el-select v-model="formData.qualityLevel" placeholder="请选择质量等级">
              <el-option label="优良" value="excellent" />
              <el-option label="合格" value="qualified" />
              <el-option label="待验收" value="pending" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="项目描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入项目描述"
        />
      </el-form-item>
      
      <el-form-item label="技术要求" prop="technicalRequirements">
        <el-input
          v-model="formData.technicalRequirements"
          type="textarea"
          :rows="3"
          placeholder="请输入技术要求"
        />
      </el-form-item>
      
      <el-form-item label="风险评估" prop="riskAssessment">
        <el-input
          v-model="formData.riskAssessment"
          type="textarea"
          :rows="3"
          placeholder="请输入风险评估"
        />
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading" v-if="!isView">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 定义组件属性
interface Props {
  modelValue: boolean
  title: string
  projectData?: any
}

// 定义事件
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  projectData: null
})

const emit = defineEmits<Emits>()

// 模拟API接口
const saveProject = async (data: any) => {
  // 模拟保存
  return { code: 200, msg: '保存成功' }
}

const updateProject = async (data: any) => {
  // 模拟更新
  return { code: 200, msg: '更新成功' }
}

// 响应式数据
const loading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  id: null,
  projectCode: '',
  reservoirName: '',
  projectName: '',
  projectType: '',
  status: 'planning',
  startDate: '',
  endDate: '',
  investment: 0,
  progress: 0,
  contractor: '',
  supervisor: '',
  projectManager: '',
  phone: '',
  designer: '',
  qualityLevel: '',
  description: '',
  technicalRequirements: '',
  riskAssessment: '',
  remark: ''
})

// 表单验证规则
const rules: FormRules = {
  projectCode: [
    { required: true, message: '请输入项目编号', trigger: 'blur' }
  ],
  reservoirName: [
    { required: true, message: '请选择水库名称', trigger: 'change' }
  ],
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  projectType: [
    { required: true, message: '请选择项目类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择项目状态', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开工时间', trigger: 'change' }
  ],
  investment: [
    { required: true, message: '请输入投资金额', trigger: 'blur' }
  ],
  contractor: [
    { required: true, message: '请输入施工单位', trigger: 'blur' }
  ],
  projectManager: [
    { required: true, message: '请输入项目经理', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isView = computed(() => props.title.includes('查看'))

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    projectCode: '',
    reservoirName: '',
    projectName: '',
    projectType: '',
    status: 'planning',
    startDate: '',
    endDate: '',
    investment: 0,
    progress: 0,
    contractor: '',
    supervisor: '',
    projectManager: '',
    phone: '',
    designer: '',
    qualityLevel: '',
    description: '',
    technicalRequirements: '',
    riskAssessment: '',
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 监听弹窗显示状态
watch(visible, (newVal) => {
  if (newVal) {
    if (props.projectData) {
      // 编辑或查看模式，填充数据
      Object.assign(formData, props.projectData)
    } else {
      // 新增模式，重置表单
      resetForm()
    }
  }
})

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    if (formData.id) {
      // 更新
      await updateProject(formData)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await saveProject(formData)
      ElMessage.success('新增成功')
    }
    
    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>